package com.jean.com.retrofittest;


import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;

/**
 * Created by jean on 2016/5/11.
 */
public class ProgressDialogHandler extends Handler {
    public static final int SHOW_PROGRESS_DIALOG = 1;
    public static final int DISMISS_PROGRESS_DIALOG = 2;
    private Context mContext;
    private ProgressDialog pd;
    private ProgressCancelListener mProgressCancelListener;
    private boolean mCancleable;

    public ProgressDialogHandler(Context context,ProgressCancelListener progressCancelListener,boolean cancleable){
        mContext = context;
        mProgressCancelListener = progressCancelListener;
        mCancleable = cancleable;
    }

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        switch (msg.what){
            case SHOW_PROGRESS_DIALOG:
                initProgressDialog();
                break;
            case DISMISS_PROGRESS_DIALOG:
                dismissProgressDialog();
                break;
        }
    }

    private void initProgressDialog(){
        if(pd == null){
            pd = new ProgressDialog(mContext);
        }
        pd.setCancelable(mCancleable);
        if(mCancleable){
            mProgressCancelListener = new ProgressCancelListener() {
                @Override
                public void onCancelProgress() {
                    mProgressCancelListener.onCancelProgress();
                }
            };
        }
        if(!pd.isShowing()){
            pd.show();
        }
    }

    private void dismissProgressDialog(){
        if(pd!=null){
            pd.dismiss();
            pd = null;
        }
    }

}
